package com.travelcloud.config.shiro;


import com.travelcloud.module.sys.entity.SysUser;
import com.travelcloud.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;


/**
 * 自定义权限匹配和账号密码匹配
 *
 * @author Zee
 * @date 2020年6月30日
 * @since v1.0
 */
@Slf4j
public class UserShiroRealm extends AuthorizingRealm {


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        MyUsernamePasswordToken usernamePasswordToken = (MyUsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = new SimpleHash("MD5", new String(usernamePasswordToken.getPassword()), username, 3).toString();
        //查询用户信息
        SysUser user = new SysUser();
        user.setUserName("admin");
        user.setPassword(password);
        user.setStatus(1);
        if (Objects.isNull(user)) {
            throw new UnknownAccountException("用户名不存在");
        }
        if (!user.getPassword().equals(password)) {
            throw new IncorrectCredentialsException("密码错误");
        }
        if (user.getStatus() != 1) {
            throw new LockedAccountException("账号过期，请联系管理员");
        }
        UserUtil.setUserSession(user);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(),
                ByteSource.Util.bytes(user.getUserName()), getName());
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.debug("权限配置");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //后期菜单配置从Session里面取
        Set<String> menus = new HashSet<>();
        authorizationInfo.setStringPermissions(menus);
        return authorizationInfo;
    }

    /**
     * 重写缓存key，否则集群下session共享时，会重复执行doGetAuthorizationInfo权限配置
     */
    @Override
    protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
        SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) principals;
        Object object = principalCollection.getPrimaryPrincipal();
        if (object instanceof SysUser) {
            SysUser user = (SysUser) object;
            return "authorization:cache:key:users:" + user.getUserId();
        }
        return super.getAuthorizationCacheKey(principals);
    }


}
